<html>
<head>
<script src="../../resources/js-test.js"></script>
</head>
<body>
<script>
description("Test the behavior of disconneced canvas recovery after a gpu context loss");

var ctx;
var lostEventHasFired = false;
var contextLostTest;
if (window.internals) {
    if (window.testRunner) {
        testRunner.dumpAsText();
        testRunner.waitUntilDone();
    }
    var canvas = document.createElement('canvas');
    canvas.addEventListener('contextlost', contextLost);
    canvas.addEventListener('contextrestored', contextRestored);
    ctx = canvas.getContext('2d');

    ctx.fillRect(0, 0, 1, 1);
    // setTimeout creates a frame barrier that locks the canvas into gpu
    // acceleration mode when running under virtual/gpu
    setTimeout(() => {
        // Now it is safe to use verifyContextLost without fearing side-effects
        // because a rendering mode was fixed.
        verifyContextLost(false);

        internals.forceLoseCanvasContext(canvas, "2d");
        if (!ctx.isContextLost()) {
            debug('<span>Aborting test: Graphics context loss did not destroy canvas contents. This is expected if canvas is not accelerated.</span>');
            if (window.testRunner) {
                testRunner.notifyDone();
            }
        } else {
            verifyContextLost(true);
        }
    }, 1);
} else {
    testFailed('This test requires window.internals.');
}

function verifyContextLost(shouldBeLost) {
    // Verify context loss experimentally as well as isContextLost()
    ctx.fillStyle = '#0f0';
    ctx.fillRect(0, 0, 1, 1);
    contextLostTest = ctx.getImageData(0, 0, 1, 1).data[1] == 0;
    if (shouldBeLost) {
        shouldBeTrue('contextLostTest');
        shouldBeTrue('ctx.isContextLost()');
    } else {
        shouldBeFalse('contextLostTest');
        shouldBeFalse('ctx.isContextLost()');
    }
}

function contextLost() {
    if (lostEventHasFired) {
        testFailed('Context lost event was dispatched more than once.');
    } else {
        testPassed('Graphics context lost event dispatched.');
    }
    lostEventHasFired = true;
    verifyContextLost(true);
}

function contextRestored() {
    if (lostEventHasFired) {
        testPassed('Context restored event dispatched after context lost.');
    } else {
        testFailed('Context restored event was dispatched before a context lost event.');
    }
    verifyContextLost(false);
    if (window.testRunner) {
        testRunner.notifyDone();
    }
}

</script>
</body>
</html>
